package com.sutong.client.service;

import com.sutong.client.config.Key;
import com.sutong.client.interceptor.SignHttpRequestInterceptor;
import com.sutong.common.model.Person;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * 调用第三方接口的客户端
 *
 * @author sutong
 * @date 2024-07-11 11:06
 */
public class Client {

    private static final String GATEWAY_HOST = "http://localhost:8888";
    private final String accessKey;
    private final String secretKey;
    private final RestTemplate restTemplate;

    public Client(String accessKey, String secretKey, RestTemplate restTemplate) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.restTemplate = restTemplate;
    }

    /**
     * 发带参数的get请求
     */
    public String getNameByGet(String name) {
        // 可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        ResponseEntity<String> res = restTemplate.getForEntity(GATEWAY_HOST + "/api/name", String.class, paramMap);
        return res.getBody();
    }

    /**
     * 发带参数的post请求
     */
    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        ResponseEntity<String> res = restTemplate.postForEntity(GATEWAY_HOST + "/api/name", null, String.class, paramMap);
        return res.getBody();
    }

    /**
     * 发带json的post请求
     */
    public String getNameByPostWithJson(Person person) {
        SignHttpRequestInterceptor.KEY.set(new Key(accessKey, secretKey));
        ResponseEntity<String> res = restTemplate.postForEntity(GATEWAY_HOST + "/api/name/user", person, String.class);
        return res.getBody();
    }
}
